package cn.bfay.service.impl;

import cn.bfay.service.LockTestService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

/**
 * LockTestServiceImpl.
 *
 * @author wangjiannan
 * @since 2021/9/26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LockTestServiceImpl implements LockTestService {
    private final RedissonClient redissonClient;

    private static Integer COUNT = 100;

    @Override
    public void testLock() {
        //获取分布式锁，只要锁的名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("lock");
        //加锁（阻塞等待），默认过期时间是30秒
        lock.lock();
        COUNT--;
        addProcessTime();
        log.info("-----------------{}", COUNT);
        lock.unlock();
    }

    private void addProcessTime() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
